<?php

namespace App\Admin\Controllers;

use App\Models\ChangePriceBill;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Http\Request;


class ChangePriceBillController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('销售调价单');
            $content->description('');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('销售调价单');
            $content->description('');
            $content->body($this->displayform()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('销售调价单');
            $content->description('');

            $content->body($this->createform());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(ChangePriceBill::class, function (Grid $grid) {
            $grid->start_time('开始时间');
            $grid->end_time('结束时间');
            $grid->create_time('创建时间 ');
            $grid->operater_id('操作人');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function displayform()
    {
        return Admin::form(ChangePriceBill::class, function (Form $form) {
            $form->display('id');
            $form->display('start_time','开始时间');
            $form->display('end_time','结束时间');
            // $form->hasMany('skuPrice', function (Form\NestedForm $form) {
            //     $form->display('sku_id','sku');
            //     $form->radio('type','调价方式')->options([0=>'客户等级',1=>'特定客户']);
            //     $form->multipleSelect('data_id', '调价单位')->options([0=>'普通',1=>'会员',2=>'个人']);
            //     $form->currency('price','价格');
            //     $form->textarea('reason','调价理由');
            // });

        });
    }

    protected function createform()
    {
        $agents= \DB::table('agent')->select('id', 'name')->get();


        function parseJson($arrays){
            $json = [];
            foreach ($arrays as $array) {
                $arr['id'] = $array->id.":::".$array->name;
                $arr['text'] = $array->name;
                array_push($json, $arr);
            }
            return $json;
        }
        $agentJson = parseJson($agents);
        $configType = HelpersController::getStateOptions('membership');
        $typeJson = [];
        $initTypeJson = [];
        foreach ($configType as $key => $value) {
            $jsonArr['id'] = $key.":::".$value;
            $jsonArr['text'] = $value;
            $initTypeJson[$key.":::".$value] = $value;
            array_push($typeJson, $jsonArr);
        }
        Admin::script('
            var data = '.json_encode($typeJson).';
            var data2 = '.json_encode($agentJson).';

            $(document).on("ifChecked","input[type=radio]", function(event){
                var that = $(this).parents(".form-group").next(".form-group").find(".data_id");
                if($(this).val() == 0){
                    that.html("");
                    that.select2({data: data})
                }else{
                    that.html("");
                    that.select2({data: data2})
                }
            });
        ');
        return Admin::form(ChangePriceBill::class, function (Form $form) use ($initTypeJson) {

            // $form->datetime('start_time','开始时间')->default(date('Y-m-d H:i:s'))->help('默认立即生效');
            // $form->datetime('end_time','结束时间')->default('9999-12-31 00:00:00')->help('默认无过期');
            $form->hasMany('skuPrice', function (Form\NestedForm $form) use ($initTypeJson) {
                $skus= \DB::table('sku')->pluck(\DB::raw("CONCAT(id,'(',name,')') as name"),'id');
                $form->select('sku_id','sku')->options($skus)->help('未填写sku的组将被忽略');
                $form->radio('type','调价方式')->options(HelpersController::getStateOptions('type'));
                $form->multipleSelect('data_id', '调价单位')->options($initTypeJson);
                $form->currency('price','价格')->symbol(' ');
                $form->textarea('remark','调价理由');
            });

        });
    }

    public function store(Request $req){
        $input = $req['skuPrice'];
        $purchase_insert_id = \DB::table('id_model')->sharedLock()->where('common_key','agent_sell_price_bill_id')->value('common_value');
        \DB::table('id_model')->where('common_key','agent_sell_price_bill_id')->increment('common_value',1);
        $id='C'.date('Ymd').str_pad($purchase_insert_id,4,"0",STR_PAD_LEFT);
        $skuPriceInsertArr = [];
        // dd($req->all());
        if(count($input) == 0){
            admin_toastr('没有任何调价','error');
            return back()->withInput();
        }
        foreach ($input as $skuPrices) {
            if(!$skuPrices['sku_id']){continue;}
            if(!$skuPrices['price']){
                admin_toastr('调价价格存在空值','error');
                return back()->withInput();
            }
            foreach($skuPrices['data_id'] as $skuPrice){
                if($skuPrice!=null){
                    $skuPriceUnit['agent_sell_price_bill_id'] = $id;
                    $skuPriceUnit['sku_id'] = $skuPrices['sku_id'];
                    $skuPriceUnit['datam_type'] = $skuPrices['type'];
                    $data = explode(':::', $skuPrice);
                    $skuPriceUnit['datam_id'] = $data[0];
                    $skuPriceUnit['datam'] = $data[1];
                    $skuPriceUnit['price'] = $skuPrices['price'];


                    $skuPriceUnit['remark'] = $skuPrices['remark'];
                    $skuPriceUnit['enable'] = 0;
                    $skuPriceUnit['created_at'] = date('Y-m-d H:i:s');
                    array_push($skuPriceInsertArr, $skuPriceUnit);
                }
            }
        }
        if(!$skuPriceInsertArr){
            admin_toastr('没有任何调价','error');
            return back()->withInput();
        }
        try{
        \DB::beginTransaction();

        $changePriceBillInsertId = \DB::table('agent_sell_price_bill')
            ->insert(
                [
                    'id' => $id,
                    // 'start_time' => $req['start_time'],
                    // 'end_time' => $req['end_time'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'operater_id' => Admin::user()->username
                ]
             );

        // dd($skuPriceInsertArr);
        \DB::table('agent_sell_price_bill_detail')
            ->insert($skuPriceInsertArr);

        \DB::commit();
        admin_toastr(trans('admin.save_succeeded'));

        $url = route('skuPrices.index');

        return redirect($url);
        }catch (Exception $e) {
            \DB::rollBack();
            dd("something wrong");

        }
    }
}
